<template>
  <view class="related-attachments">
    <view class="attachments-title">相关附件</view>
    
    <!-- 附件列表 -->
    <view v-if="attachmentList && attachmentList.length > 0" class="attachment-list">
      <view 
        v-for="(attachment, index) in attachmentList" 
        :key="index"
        class="attachment-item"
        @click="handleAttachmentClick(attachment)"
      >
        <u-icon name="file-text" size="16" color="#3B75FA"></u-icon>
        <text class="attachment-name">{{ attachment.displayName }}</text>
        <u-icon name="arrow-right" size="14" color="#999"></u-icon>
      </view>
    </view>
    
    <view v-else class="no-attachment">
      暂无相关附件
    </view>
  </view>
</template>

<script>
import { parseAttachmentList, handleFile } from '@/util/function'

export default {
  name: 'Relatedaccessories',
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      attachmentList: []
    }
  },
  watch: {
    fileUrl: {
      handler(newVal) {
        this.parseAttachments(newVal)
      },
      immediate: true
    }
  },
  methods: {
    // 解析附件列表
    parseAttachments(fileUrl) {
      if (!fileUrl) {
        this.attachmentList = []
        return
      }
      
      try {
        this.attachmentList = parseAttachmentList(fileUrl)
      } catch (error) {
        console.error('解析附件列表失败:', error)
        this.attachmentList = []
      }
    },
    
    // 处理附件点击
    handleAttachmentClick(attachment) {
      if (!attachment || !attachment.realUrl) {
        uni.showToast({
          title: '附件链接无效',
          icon: 'none'
        })
        return
      }
      
      // 使用公共文件处理函数
      handleFile(attachment.realUrl, attachment.displayName)
        .then(() => {
          console.log('文件处理成功')
        })
        .catch((error) => {
          console.error('文件处理失败:', error)
          uni.showToast({
            title: '文件打开失败',
            icon: 'none'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.related-attachments {
  width: 100%;
  background: #fff;
  border-radius: 18rpx;
  padding: 30rpx 20rpx;
  margin: 20rpx 4rpx 0 4rpx;
  box-shadow: 0rpx 0rpx 27rpx 0rpx rgba(0,0,0,0.03);
}

.attachments-title {
  font-weight: 600;
  font-size: 30rpx;
  color: #000000;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.attachment-list {
  margin-top: 20rpx;
  padding: 10rpx 0;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f8f9fa;
  }
}

.attachment-name {
  flex: 1;
  margin-left: 12rpx;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-attachment {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
